package com.project.core.shiro;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import com.project.core.model.Permission;
import com.project.core.model.Role;
import com.project.core.model.Users;
import com.project.core.service.IUsersService;

public class MonitorRealm extends AuthorizingRealm{
	
	@Autowired
	private IUsersService userService;

	/**
	 * 授权
	 */
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		String username = (String) principals.getPrimaryPrincipal();
		Set<Role> roleSet = userService.getUserById(username).getRoleSet();
		// 角色名集合
		Set<String> roles = new HashSet<String>();
		// 权限名集合
		Set<String> permissions = new HashSet<String>();
		
		Iterator<Role> it = roleSet.iterator();
		while (it.hasNext()) {
			roles.add(it.next().getName());
			for (Permission per:it.next().getPermissionSet()) {
				permissions.add(per.getName());
			}
		}
		
		SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
		authorizationInfo.addRoles(roles);
		authorizationInfo.addStringPermissions(permissions);
		return authorizationInfo;
	}

	/**
	 * 验证
	 */
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken token) throws AuthenticationException {
		/*UsernamePasswordToken autotoken = (UsernamePasswordToken) token;*/
		String username = (String) token.getPrincipal();
		Users user = userService.getUserById(username);
		if(null==user){
			throw new UnknownAccountException("该账号不存在!");
		}
		
		/** 交给AuthenticatingRealm使用CredentialsMatcher进行密码匹配 */
		SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user.getUsersname(), user.getUserspwd(), getName());
		return info;
	}
	
	@Override  
    public String getName() {
        return getClass().getName();  
    }
	
}